import service from "@/utils/request";
import { ElMessage } from "element-plus";
import { saveAs } from "file-saver";
import { ElLoading } from "element-plus";
import { nextTick } from "vue";
import { tansParams } from "@/utils/yixia";

let downloadLoadingInstance;

/**
 * 导出下载文件
 * @param url 下载文件地址
 * @param params 查询参数
 * @param filename 文件名
 */
export function download(url: string, params: any, filename: string) {
  console.log("yimeng");
  console.log(url);
  console.log(params);
  console.log(filename);

  downloadLoadingInstance = ElLoading.service({
    text: "正在下载数据，请耐心等待...",
    spinner: "Loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
  return service.post(
    url,
    params,
    {
      transformRequest: params => {
        return tansParams(params)
      },
      responseType: "blob",
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then(async (res: any) => {
    console.log(res);
    await saveAs(res, filename);
    nextTick( () => {
      // Loading should be closed asynchronously
      downloadLoadingInstance.close();
    });
  }).catch((e) => {
    ElMessage.error("下载文件出错，请联系管理员！");
    console.log(e.message);
    nextTick(() => {
      // Loading should be closed asynchronously
      downloadLoadingInstance.close();
    });
  });

}


/*
export function transParams(params: any) {
  let result = '';

  for (const  propName of Object.keys(params)){
    const value = params[propName]
    let part = propName + '='
    if(value !== null && typeof value !== 'undefined'){
      result += part + value + '&'
    }
  }
  return result;
}
*/
